import { observer } from 'mobx-react-lite';
import React, { useState, useRef, useEffect } from 'react';
import { Drawer, Form, Button, Dialog, Transfer, Table, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { TitleGrid, FieldsGrid, ENUMS, DATETIME_TEXT } from '../../stores/definitions';
import { useStore } from '@/hooks';
import { observable } from 'mobx';
import styles from './index.module.scss';

const FromItem = Form.Item;

const Index = ({ visible, task, onCancel, modal, onSubmit }) => {
  const { scTaskStore: store } = useStore();
  const [alteration] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const {
    orderIds,
    id,
  } = task || {};

  const [state, setState] = useState({
    newOrders: [],
    taskOrders: [],
  });

  const [selectState, setSelectState] = useState({
    newOrders: [],
    taskOrders: [],
  });
  const [cloneIds, setCloneIds] = useState([]);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (JSON.stringify(task) !== '{}') {
      const data = task;
      _.assign(alteration, data);
      setCloneIds(orderIds);
      editCtx.origin = _.cloneDeep(task);
      (async () => {
        await init(orderIds);
      })();
    }
  }, [task]);

  /**
   * 初始化表格数据
   */
  async function init(ids) {
    const taskOrders = await store.getScOrders({ orderIds: ids });
    const newOrders = await store.getScOrdersInfo(id);
    const { tickets = [] } = toJS(alteration);
    // 初始化计数器
    const orderCountMap = {};

    // 统计每个 orderId 的出现次数
    tickets.forEach((ticket) => {
      const { orderId } = ticket; // 假设 tickets 中的每个对象都有一个 orderId 字段
      if (orderId) {
        orderCountMap[orderId] = (orderCountMap[orderId] || 0) + 1;
      }
    });

    // 映射 taskOrders 并添加出现次数
    const transferOrder = taskOrders.map((p) => {
      const count = orderCountMap[p.id] || 0; // 获取当前订单 ID 的出现次数
      return {
        ...p,
        ticketCount: count, // 添加 ticketCount 字段
      };
    });
    setState({
      newOrders,
      taskOrders: transferOrder,
    });
  }

  const newColumns = [
    {
      title: t`新订单`,
      dataIndex: 'id',
      width: 360,
      align: 'center',
      cell: (v, __, r) => {
        const { ticketInfo } = r?.scOrder;
        return (
          <div>
            <span>{v}</span>
            <span style={{ color: 'red' }}>{` (${ticketInfo.filter((p) => p.state !== '0' && p.taskFlag === false).length})`}</span>
          </div>
        );
      },
    },
    {
      title: t`预约人`,
      dataIndex: 'subscribeName',
      width: 200,
      align: 'center',
      cell: (v, __, r) => {
        const { subscribeName } = r?.scOrder;
        return <span>{subscribeName}</span>;
      },
    },
    {
      title: t`上车时间`,
      dataIndex: 'shiftTime',
      width: 200,
      align: 'center',
      cell: (v, __, r) => {
        const { shiftTime } = r?.scOrder;
        return <span>{DATETIME_TEXT(shiftTime)}</span>;
      },
    },
  ];

  const ordersColumns = [
    {
      title: t`任务中订单`,
      dataIndex: 'id',
      width: 330,
      align: 'center',
      cell: (v, __, r) => {
        const { ticketCount } = r;
        return (
          <div>
            <span>{v}</span>
            <span style={{ color: 'red' }}>{` (${ticketCount})`}</span>
          </div>
        );
      },
    },
    {
      title: t`预约人`,
      dataIndex: 'subscribeName',
      width: 220,
      align: 'center',
      cell: (v, __, r) => {
        const { subscribeName } = r?.scOrder;
        return <span>{subscribeName}</span>;
      },
    },
    {
      title: t`上车时间`,
      dataIndex: 'shiftTime',
      width: 220,
      align: 'center',
      cell: (v, __, r) => {
        const { shiftTime } = r?.scOrder;
        return <span>{DATETIME_TEXT(shiftTime)}</span>;
      },
    },
  ];

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(alteration, name, value);
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleOnChange = async (__, ___, extra) => {
    const { direction, movedValue } = extra;
    if (direction === 'left') {
      await handleRemoveOrder(movedValue[0]);
    } else {
      await handleAddOrder(movedValue[0]);
    }
  };

  /**
   * 任务中加入订单
   * @param {*} i
   * @param {*} r
   */
  const handleAddOrder = async (r) => {
    if (r?.taskIds && r?.taskIds?.length > 0) {
      Dialog.confirm({
        title: t`此订单已在其他任务中`,
        content: t`是否继续添加？`,
        onOk: async () => await onOk(r),
      });
    } else {
      Dialog.confirm({
        content: t`确定加入订单？`,
        onOk: async () => await onOk(r),
      });
    }
  };

  async function onOk(r) {
    const taskTicketLength = state.taskOrders.reduce((acc, item) => {
      acc += item?.ticketCount;
      return acc;
    }, 0);
    const currentTaskTicketLength = taskTicketLength + r?.scOrder?.ticketInfo.filter((p) => p.state !== '0' && p.taskFlag === false).length;
    if (currentTaskTicketLength > 7) {
      return Message.warning({ content: t`加入此订单后车票数量将超过7张, 请更换订单` });
    }
    try {
      await store.taskJoinOrder({
        orderId: r?.id,
        taskId: id,
      });
      // 需要先在ids中加入id
      const ids = _.cloneDeep(cloneIds);
      ids.push(r?.id);
      setCloneIds(ids);
      await init(ids);
      Message.success({ content: t`加入成功` });
    } catch (error) {
      Message.error({ content: t`加入失败`, duration: 7000 });
      throw error;
    }
  }

  /**
   * 任务中移除订单
   * @param {*} i
   * @param {*} r
   */
  async function handleRemoveOrder(r) {
    if (cloneIds.length === 1) {
      Dialog.confirm({
        content: t`移除此订单后任务将解散, 是否继续移除?`,
        onOk: async () => {
          await removeOrder(r);
        },
      });
    } else {
      Dialog.confirm({
        content: t`确定移除订单?`,
        onOk: async () => await removeOrder(r),
      });
    }
  }

  async function removeOrder(r) {
    try {
      await store.taskRemoveOrder({
        orderId: r?.id,
        taskId: id,
      });
      // 需要先过滤掉任务中当前移除的订单id
      const ids = _.cloneDeep(cloneIds);
      const filterIds = ids.filter((p) => p !== r?.id);
      setCloneIds(filterIds);
      await init(filterIds);
      Message.success({ content: t`移除成功` });
      store._mainArgs.query();
      // handleCancel();
    } catch (error) {
      Message.error({ content: t`移除失败`, duration: 7000 });
      throw error;
    }
  }

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => {
          onCancel?.();
          store._mainArgs.query({});
        },
      });
      return;
    }
    onCancel?.();
    store._mainArgs.query({});
  };

  return (
    <Drawer
      visible={visible}
      title={t`编辑订单`}
      onClose={() => handleCancel()}
      closeMode={['esc', 'mask', 'close']}
      style={{ maxWidth: '90%' }}
      width="100%"
    >
      <Form
        inline
        isPreview={isViewMode}
        {...formProps}
        value={alteration}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <TitleGrid title={t`任务信息`} />
        <FieldsGrid
          formData={alteration}
          mode={'view'}
          fields={[
            'id',
            'crDate',
            'orderBaseModel.subscribeName',
            'orderBaseModel.subscribePhone',
            'orderBaseModel.predictBeginDate',
            'orderBaseModel.predictEndDate',
            'orderBaseModel.portTypeText',
            'orderBaseModel.mileage',
            'orderBaseModel.startMainAreaText',
            'orderBaseModel.startStationName',
            'orderBaseModel.endMainAreaText',
            'orderBaseModel.endStationName',
            'orderBaseModel.beginName',
            'orderBaseModel.endName',
          ]}
        />
        <div className={styles.transfer_container} >
          <Transfer
            // dataSource={[
            //   ...state.newOrders,
            //   ...state.taskOrders,
            // ]}
            titles={[
              <>
                <Button text>{'新订单'}</Button>
                <Button type="primary" size="small" style={{ marginLeft: 10 }} onClick={() => setSelectState((pre) => ({ ...pre, newOrders: [] }))}>{t`重置`}</Button>
              </>,
              <>
                <Button text>{'任务中订单'}</Button>
                <Button type="primary" size="small" style={{ marginLeft: 10 }} onClick={() => setSelectState((pre) => ({ ...pre, taskOrders: [] }))}>{t`重置`}</Button>
              </>,
            ]}
            onChange={handleOnChange}
            showCheckAll={false}
          >
            {({ position, onChange }) => {
              const currentDataSource = position === 'left' ? state.newOrders : state.taskOrders;
              const selectedKeys = position === 'left' ? selectState.newOrders : selectState.taskOrders;
              return (
                <Table
                  dataSource={currentDataSource}
                  value={currentDataSource}
                  // total={currentDataSource.length}
                  hasBorder={false}
                  rowSelection={{
                    mode: 'single',
                    selectedRowKeys: selectedKeys,
                    value: selectedKeys,
                    onChange: (selectedRowKeys, records) => {
                      setSelectState((prevState) => ({
                        ...prevState,
                        [position === 'left' ? 'newOrders' : 'taskOrders']: selectedRowKeys,
                      }));
                      onChange(position, records);
                    },
                  }}
                  columns={position === 'left' ? newColumns : ordersColumns}
                />
              );
            }}
          </Transfer>
        </div>
        <DrawerFooter>
          <FromItem>
            {/* {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>} */}
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
    </Drawer>
  );
};

export default observer(Index);
